package com.hnichr.ping.common.service.impl;

import com.hnichr.ping.common.DictEnum;
import com.hnichr.ping.common.service.SendService;
import com.hnichr.ping.common.vo.SendResultVo;
import com.hnichr.ping.common.vo.SmsSendVo;
import com.hnichr.ping.sms.entity.SmsChannel;
import com.hnichr.ping.sms.service.SmsSendService;
import com.hnichr.ping.tenant.entity.Tenant;
import com.hnichr.ping.tenant.service.TenantBizTypeService;
import com.hnichr.ping.tenant.service.TenantService;
import com.hnichr.ping.tenant.entity.TenantBizType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SendServiceImpl implements SendService {

    @Autowired
    private SmsSendService smsSendService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private TenantBizTypeService tenantBizTypeService;

    @Override
    public SendResultVo sendSms(SmsSendVo smsSendVo) {
        Tenant tenant = tenantService.getTenantByAppKey(smsSendVo.getAppKey());
        if(tenant==null){
            return SendResultVo.failed("租户不存在");
        }
        if(!StringUtils.equals(tenant.getStatus(), DictEnum.STATUS.OPEN.getCode())){
            return SendResultVo.failed("租户已禁用");
        }

        SendResultVo checkResult = smsSendService.paramVerify(smsSendVo,tenant.getAppSecert());
        if(!checkResult.isSuccess()){
            return SendResultVo.failed(checkResult.getMsg());
        }

        TenantBizType tenantBizType = tenantBizTypeService.getByTenantIdAndBizType(tenant.getId(),DictEnum.MESSAGE_TYPE.SMS.getCode());
        if(tenantBizType==null){
            return SendResultVo.failed("该租户未开通短信发送业务");
        }

        SmsChannel channel = smsSendService.getSmsChannel(tenantBizType.getChannelCode());
        if(channel==null){
            return SendResultVo.failed("无可用发送通道");
        }
        return smsSendService.smsSend(smsSendVo, tenant,channel,tenantBizType);
    }
}
